package com.jhgsys.internal.common.controller;

import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.utils.Plupload;
import com.jhgsys.internal.common.utils.PluploadUtil;
import com.jhgsys.internal.common.utils.UploadPathUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * UEditor文件上传辅助类
 * @author chenweihua
 */
@Controller()
public class FileUploaderController extends BaseController {

	public static String MSG_ERROR_FILE_TYPE = "文件类型不正确！";
	public static String MSG_ERROR_NO_FILE = "未包含上传文件！";
	// 文件允许格式
	private final String[] allowImageFiles = {".gif", ".png", ".jpg", ".jpeg", ".bmp" };
	private final String[] allowVideoFiles = {".swf", ".wmv", ".mpg", ".m4v", ".mp4", ".flv", ".3gp", ".avi", ".rmvb", ".mkv"};
	private final String[] allowOtherFiles = {".rar", ".zip", ".pdf", ".txt", ".ppt", ".pptx", ".doc", ".docx", ".xls", ".xlsx", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
	// 文件大小限制，单位KB
	//private int maxSize = 10000;

	//private HashMap<String, String> errorInfo = new HashMap<String, String>();

	@RequestMapping(value = "upload/image", method = RequestMethod.POST)
	@ResponseBody
	public FebsResponse uploadImage(Plupload plupload, HttpServletRequest request) {
		if (!checkFileType(plupload.getName(), allowImageFiles)) {
			return new FebsResponse().fail().message("不支持的文件类型！");
		}
		if(StringUtils.isBlank(plupload.getFilePath())){
			plupload.setFilePath("images");
		}
		FebsResponse objects = fileUpCommon(plupload, request, plupload.getFilePath());
		return objects;
	}


	@RequestMapping(value = "upload/file", method = RequestMethod.POST)
	@ResponseBody
	public FebsResponse uploadFile(Plupload plupload, HttpServletRequest request) {
		if (!checkFileType(plupload.getName(), allowOtherFiles)) {
			return new FebsResponse().fail().message("不支持的文件类型！");
		}
		FebsResponse objects = fileUpCommon(plupload, request, "files");
		return objects;
	}

	@RequestMapping(value = "upload/video", method = RequestMethod.POST)
	@ResponseBody
	public FebsResponse uploadVideo(Plupload plupload, HttpServletRequest request) {
		if (!checkFileType(plupload.getName(), allowVideoFiles)) {
			return new FebsResponse().fail().message("不支持的文件类型！");
		}
		FebsResponse objects = fileUpCommon(plupload, request, "video");
		return objects;
	}

	public static FebsResponse fileUpCommon(Plupload plupload, HttpServletRequest request, String path) {
		plupload.setRequest(request);
		try {
			String videoPath = path + "/" + dateFormat();
			File dir = new File(UploadPathUtil.getRootPath() + videoPath);
			//上传文件
			PluploadUtil.upload(plupload, dir);
			//判断文件是否上传成功（被分成块的文件是否全部上传完成）
			if (PluploadUtil.isUploadFinish(plupload)) {
				//File uploadFile = new File(dir.getPath(), plupload.getFileName());
				//String imageName = plupload.getFileName().substring(plupload.getFileName().lastIndexOf(".") + 1) + ".jpg";
				//Video2ImageUtil.randomGrabberFFmpegImage(uploadFile.getPath(), dir.getPath(), imageName);
				Map<String, Object> data = new HashMap<>();
				data.put("fileName", plupload.getFileName());
				data.put("filePath", "files/" + videoPath + "/" + plupload.getFileName());
				data.put("smallPath", "files/" + videoPath + "/" + plupload.getSmallFileName());
				data.put("message", plupload.getChunk() + "," + plupload.getName() + "," + plupload.getChunks());
				return new FebsResponse().success().data(data);
			} else {
				return new FebsResponse().success().message(plupload.getChunk() + "," + plupload.getName() + "," + plupload.getChunks());
			}
		} catch (Exception e) {
			return new FebsResponse().fail().message("文件上传失败！Error：" + e.getMessage());
		}
	}

	private static String dateFormat() {
		String formatDay = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
        return formatDay;
		//return formatDay.substring(0, 4) + "/" + formatDay.substring(4, 6) + "/" + formatDay.substring(6);
	}

	/**
	 * 文件类型判断
	 *
	 * @param fileName
	 * @return
	 */
	private static boolean checkFileType(String fileName, String[] allowFiles) {
		Iterator<String> type = Arrays.asList(allowFiles).iterator();
		while (type.hasNext()) {
			String ext = type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取文件扩展名
	 *
	 * @return string
	 */
	private String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 根据传入的虚拟路径获取物理路径
	 *
	 * @param path
	 * @return
	 */
	private String getPhysicalPath(String path) {
		return new File(UploadPathUtil.getRootPath()) + "/" + path;
	}
}
